﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using MvcShop.Models;
using System.Configuration;
using System.Linq.Expressions;

namespace MvcShop.Models.Repositories
{
    

    public class BaseRepository
    {
        /// <summary>
  	    /// 取得 EntityConnection
  	    /// </summary>
  	    /// <param name="connectionString">连接字符串</param>
  	    /// <returns>EntityConnection</returns>
        public static EntityConnection GetEntityConnection(string connectionString)
        {
            EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
            ecsb.Metadata = string.Format(@"res://*/{ }.csdl|res://*/{ }.ssdl|res://*/{0}.msl", "Demo.DA.TestModel");
            ecsb.Provider = "System.Data.SqlClient"; ////不可省略           
            ecsb.ProviderConnectionString = connectionString;
            EntityConnection ec = new EntityConnection(ecsb.ToString());

            return ec;
        }

        public BaseRepository()
        {
            var conn = GetEntityConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
            sse=new SouthShopEntities1(conn);
        }

        public static SouthShopEntities1 sse;

        /// <summary>
 	    /// 让 EF 支持类似 SQL "IN" 的语法   ContainsExpression
 	    /// </summary>  
 	    public static Expression<Func<TElement, bool>> ContainsExpression<TElement, TValue>(
 	            Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
 	    {
 	        if (null == valueSelector)
 	        {
 	            throw new ArgumentNullException("valueSelector");
 	        }
  
 	        if (null == values)
            {
 	            throw new ArgumentNullException("values");
 	        }
 	 
 	        ParameterExpression p = valueSelector.Parameters.Single();
 	        
 	        if (!values.Any())
 	        {
 	            return e => false;
 	        }
 	 
 	        var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
 	        var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
 	        return Expression.Lambda<Func<TElement, bool>>(body, p);
 	    }
    } 
}
